package chidist_to_prob;


#_________________________________________________________________________________________


#		This is a wrapper around Zhiheng Yang's chi dist programme



#			uncomment out test() and run this module directly to see it in action


#			This module runs the c++ binary (once) when the module loads, 
# 				and pipes parameters in / results out every time the function
#               is called.

#			This is loads faster than running hypergeometric_cdf_P
#				each time the function is called


#			The downside is that the code 
#				(1) uses OPC::Open2 which is a bit rocket science
#				(2) depends on the OS pipes working properly
#				(3) depends on an immediate response from the c++ programme
#                        i.e. no buffering



#_________________________________________________________________________________________

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(   chiddist_to_prob);






use strict;
use IPC::Open2;



my ($results_chidist, $input_chidist);


my $process_id;
BEGIN
{
	my $BINARY_PATH = "/net/cpp-group/Leo/bin";

	# handle autovivification
    $process_id = open2($results_chidist, $input_chidist, $BINARY_PATH."/chi2");
}


END
{
	close($input_chidist);
	close($results_chidist);
}

sub chiddist_to_prob($$)
{
	my ($df, $chi) = @_;
	die unless defined $df;
	die unless defined $chi;
	print $input_chidist "$df $chi\n";
	my $results = <$results_chidist>;
#	my $results = "";
	chomp $results;
	return $results;
}

my %testvalues =( 1 => [0.0000, 0.0010, 0.0158, 0.4549, 2.7055, 3.8415, 6.6349, 10.8276]  ,
				2 => [ 0.0100, 0.0506, 0.2107, 1.3863, 4.6052, 5.9915, 9.2103, 13.8155 ],
				3 => [ 0.0717, 0.2158, 0.5844, 2.3660, 6.2514, 7.8147, 11.3449, 16.2662]);


sub test()
{
	for my $df (keys %testvalues)
	{
		for my $chi(@{$testvalues{$df}})
		{
			print "df = $df, chi = $chi, p =", chiddist_to_prob($df, $chi), "\n";
		}
	}
}
#	uncomment out to test
# 
#test();
1;


